package 基础;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;
    TcpEchoClient(String serverIp,int serverPort) throws IOException {
//        这里不需要将serverIP和serverPort在类中保存
//        因为tcp有链接，socket会保存好这两个值
        socket = new Socket(serverIp,serverPort);
    }

    public void start(){
        System.out.println("客户端启动");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            //客户端输入的数据
            Scanner scannerConsole = new Scanner(System.in);
            //通过网络读取
            Scanner scannerNetwork = new Scanner(inputStream);
            //像服务器发送请求
            PrintWriter writer = new PrintWriter(outputStream);
            while(true){
                System.out.print("->");
                //客户端没有输入
                if(!scannerConsole.hasNext()){
                    break;
                }
//                1. 从控制台读取请求
                String request = scannerConsole.next();
//                2.将请求发送给服务端
                writer.println(request);
                //冲刷缓冲区
                writer.flush();
//                3.接受服务端返回的响应
                //从数据缓冲区中读取出内容
                String respond = scannerNetwork.next();
//                4.将响应显示在控制台
                System.out.println(respond);

            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
